package filter;

import zut.DO.ResultDO;
import zut.DO.UserDO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    private String[] pathList;

    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{
        HttpServletRequest hreq = (HttpServletRequest)request;
        HttpServletResponse hresp = (HttpServletResponse)response;
        String requestPath = hreq.getServletPath();
        HttpSession session = hreq.getSession();
        ResultDO<UserDO> r = (ResultDO<UserDO>)session.getAttribute("user");
        System.out.println(requestPath);
        if(containsPath(requestPath)||r!=null) {
            System.out.println("放行");
            chain.doFilter(request, response);
        }else {
            System.out.println("bufangxing");
        }
    }

    public void init(FilterConfig fConfig) throws ServletException{
        // 获取要放行的路径列表
        String values = fConfig.getInitParameter("paths");
        System.out.println(values+"值是");
        pathList = values.split(",");
    }

    public boolean containsPath(String path) {
        for(String p : pathList) {
            if(p.equals(path)) {
                return true;
            }
        }
        return false;
    }
}
